﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Rodunu.Business.Interfaces;
using Rodunu.Business.Models.Movies;
using Rodunu.Clients.WPF.Search;

namespace Rodunu.Clients.WPF
{
	/// <summary>
	/// Interaction logic for CollectionSearchResults.xaml
	/// </summary>
	public partial class CollectionSearchResults
    {
        private readonly string _searchFor;
        private readonly BackgroundWorker _backgroundWorker;
        private readonly StackPanel _moviesInCollection;
	    private readonly ICollection _myCollection;

        public CollectionSearchResults(string searchFor, ICollection myCollection)
		{
            InitializeComponent();

            _myCollection = myCollection;
            _searchFor = searchFor;

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += _backgroundWorker_DoWork;
            _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;
            _backgroundWorker.RunWorkerAsync(_searchFor);

            _moviesInCollection = new StackPanel();
            _moviesInCollection.Margin = new Thickness(10, 0, 0, 0);
        }

        void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LayoutRoot.Children.Remove(Loader);

            if (e.Result != null)
            {
                NumberOfResults.Content = ((IList<Title>)e.Result).Count;

                if (((IList<Title>)e.Result).Count > 9)
                {
                    var scrollViewer = new ScrollViewer();
                    //scrollViewer.Height = 200;
                    scrollViewer.Content = _moviesInCollection;

                    LayoutRoot.Children.Add(scrollViewer);
                    Grid.SetRow(scrollViewer, 1);
                }
                else
                {
                    LayoutRoot.Children.Add(_moviesInCollection);
                    Grid.SetRow(_moviesInCollection, 1);
                }

                foreach (var item in (IList<Title>)e.Result)
                {
                    _moviesInCollection.Children.Add(new SearchResultButton(item.Name, Convert.ToInt32(item.Id)));
                }
            }
        }

        void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = _myCollection.SearchTitles(Convert.ToString(e.Argument));
        }
	}
}